package util

import (
	"log"
	"time"

	"github.com/go-ini/ini"
)

type Server struct {
	RunMode      string
	HttpPort     int
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

var ServerSetting = &Server{}

type Database struct {
	Type        string
	User        string
	Password    string
	Host        string
	Name        string
	TablePrefix string
}

var DatabaseSetting = &Database{}

type Redis struct {
	Host        string
	Password    string
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
}

var RedisSetting = &Redis{}

type Zap struct {
	RunningFilename string
	ErrorsFilename  string
	FileSize        int
	OldFileNumbers  int
	MaxAge          int
}

var ZapSetting = &Zap{}

type Cache struct {
	ExpireTime time.Duration
	CacheSize  int
	Algorithm  string
}

var CacheSetting = &Cache{}

var cfg *ini.File

// SettingSetup 启动配置
func SettingSetup() {
	var err error
	cfg, err = ini.Load("./conf/app.ini")
	if err != nil {
		log.Fatal("启动配置失败: %v", err)
	}

	mapTo("server", ServerSetting)
	mapTo("database", DatabaseSetting)
	mapTo("redis", RedisSetting)
	mapTo("zap", ZapSetting)
	mapTo("cache", CacheSetting)

	ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second
	ServerSetting.WriteTimeout = ServerSetting.WriteTimeout * time.Second
	RedisSetting.IdleTimeout = RedisSetting.IdleTimeout * time.Second
	CacheSetting.ExpireTime = CacheSetting.ExpireTime * time.Minute
}

// mapTo map section
func mapTo(section string, v interface{}) {
	err := cfg.Section(section).MapTo(v)
	if err != nil {
		log.Fatal("配置【%s】出错: %v", section, err)
	}
}
